package com.hmo.http;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;

import androidx.leanback.widget.ArrayObjectAdapter;

import com.alibaba.fastjson.JSONObject;
import com.hmo.appshop.AppBean;
import com.hmo.appshop.DetailsActivity;

import org.jetbrains.annotations.NotNull;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import java.util.concurrent.TimeUnit;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class BaseRequest {
    private String TAG="BaseRequest";
    private OkHttpClient okHttpClient;

    public BaseRequest() {
        okHttpClient=OkHttpClientBean.getOkHttpClient();
    }

    public void backJson(final ServiceEnum serviceEnum, final JsonResponseCallBack callback){
        Request request = new Request.Builder()
                .url(serviceEnum.getUrl())
                .method(serviceEnum.getMethod(),null)
                .build();

        okHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(@NotNull Call call, @NotNull IOException e) {
                callback.requestFailure(0,e.getMessage());
                //e.printStackTrace();
                //okHttpClient.newCall(call.request()).enqueue(this);
                //Log.d(TAG, serviceEnum.getUrlFlag()+"重连");
            }

            @Override
            public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
                Log.d(TAG, response.code()+serviceEnum.getUrlFlag());
                if (response.isSuccessful()){
                    JSONObject parse =JSONObject.parseObject(response.body().string());

                    Integer code= Integer.valueOf(parse.get("code").toString());

                    if (code==200)
                        callback.requestSuccess(parse);
                    else {
                        callback.requestFailure(code,parse.getString("message"));
                    }
                }else {
                    callback.requestFailure(response.code(),response.message());
                }
            }
        });
    }

    public void backBitmaps(List<AppBean> appBean){

        ServiceEnum getImage = ServiceEnum.getImage;
        for (final AppBean bean:appBean){
            Request request = new Request.Builder()
                    .url(getImage.getUrl()+bean.getLogoName())
                    .method(getImage.getMethod(),null)
                    .build();
            okHttpClient.newCall(request).enqueue(new Callback() {
                @Override
                public void onFailure(@NotNull Call call, @NotNull IOException e) {
                    //okHttpClient.newCall(call.request()).enqueue(this);
                }

                @Override
                public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
                    if (response.isSuccessful()){
                        InputStream inputStream = response.body().byteStream();
                        Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
                        inputStream.close();
                        bean.setLogo(bitmap);
                        response.close();
                    }else {

                    }
                }
            });
        }
    }

    public void backBitmaps(final ArrayObjectAdapter data){
        final ServiceEnum getImage = ServiceEnum.getImage;
        for (int i=0;i<data.size();i++){
            final AppBean appBean = (AppBean) data.get(i);

            final Request request = new Request.Builder()
                    .url(getImage.getUrl()+appBean.getLogoName())
                    .method(getImage.getMethod(),null)
                    .build();
            okHttpClient.newCall(request).enqueue(new Callback() {
                @Override
                public void onFailure(@NotNull Call call, @NotNull IOException e) {
                    //okHttpClient.newCall(call.request()).enqueue(this);
                    Log.d(TAG, getImage.getUrlFlag()+"重连");
                }

                @Override
                public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
                    if (response.isSuccessful()){
                        Log.d(TAG, response.code()+"picture");
                        InputStream inputStream = response.body().byteStream();
                        Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
                        inputStream.close();

                        appBean.setLogo(bitmap);

                        new Handler(Looper.getMainLooper()).postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                data.notifyItemRangeChanged(appBean.getId(),1);
                            }
                        },1000);


                        response.close();
                    }else {

                    }
                }
            });


        }

    }

    public void backBitmaps(String[] pictures,final ArrayObjectAdapter bitmaps){

        final ServiceEnum getImage = ServiceEnum.getImage;
        if (pictures==null)
            return;
        for (String picture:pictures){
            final Request request = new Request.Builder()
                    .url(getImage.getUrl()+picture)
                    .method(getImage.getMethod(),null)
                    .build();
            okHttpClient.newCall(request).enqueue(new Callback() {
                @Override
                public void onFailure(@NotNull Call call, @NotNull IOException e) {
                    //okHttpClient.newCall(call.request()).enqueue(this);
                    Log.d(TAG, getImage.getUrlFlag()+"重连");
                }

                @Override
                public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
                    if (response.isSuccessful()){
                        Log.d(TAG, response.code()+"picture");
                        InputStream inputStream = response.body().byteStream();
                        final Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
                        inputStream.close();

                        DetailsActivity.bitmaps.add(bitmap);


                        new Handler(Looper.getMainLooper()).post(new Runnable() {
                            @Override
                            public void run() {
                                bitmaps.add(bitmap);
                                DetailsActivity.pagerViewAdapter.notifyDataSetChanged();
                            }
                        });

                        response.close();
                    }else {

                    }
                }
            });
        }
    }

    public Call download(String apk, final DownloadListener downloadListener, final Callback callback){

        Request request = new Request.Builder()
                .url(ServiceEnum.getApk.getUrl()+apk)
                .build();

        // 重写ResponseBody监听请求
        Interceptor interceptor = new Interceptor() {
            @Override
            public Response intercept(Chain chain) throws IOException {
                Response originalResponse = chain.proceed(chain.request());
                return originalResponse.newBuilder()
                        .body(new DownloadResponseBody(originalResponse, downloadListener))
                        .addHeader("connection","close")
                        .build();
            }
        };

        OkHttpClient client = new OkHttpClient().newBuilder().connectTimeout(60, TimeUnit.MINUTES)
                .readTimeout(60, TimeUnit.MINUTES)
                .writeTimeout(60, TimeUnit.MINUTES)
                .addNetworkInterceptor(interceptor)
                .retryOnConnectionFailure(true)
                .build();

        // 发起请求
        Call call = client.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(@NotNull Call call, @NotNull IOException e) {
                //okHttpClient.newCall(call.request()).enqueue(this);
                callback.onFailure(call,e);
            }

            @Override
            public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
                callback.onResponse(call,response);
            }
        });
        return call;
    }
}
